<template>
  <div class="app-container">
    <form-header />
    <el-form ref="form" :model="form" :rules="rules" label-width="140px">
      <el-form-item label="活动名称" prop="activityName">
        <el-input v-model="form.activityName" clearable placeholder="请输入活动名称" />
      </el-form-item>
      <el-form-item label="优惠券名称" prop="couponName">
        <el-input v-model="form.couponName" clearable placeholder="请输入优惠券名称" />
      </el-form-item>
      <el-form-item label="活动时间" required>
        <el-col :span="5">
          <el-form-item prop="activityStartTime">
            <el-date-picker v-model="form.activityStartTime" type="date" placeholder="选择开始日期" style="width: 100%;" :picker-options="pickerOptions" />
          </el-form-item>
        </el-col>
        <el-col class="line" :span="1" style="text-align:center;">-</el-col>
        <el-col :span="5">
          <el-form-item prop="activityEndTime">
            <el-date-picker v-model="form.activityEndTime" type="date" placeholder="选择结束日期" style="width: 100%;" :picker-options="pickerOptions" />
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="优惠券有效时间" required>
        <el-col :span="5">
          <el-form-item prop="couponStartTime">
            <el-date-picker v-model="form.couponStartTime" type="date" placeholder="选择开始日期" style="width: 100%;" :picker-options="pickerOptions" />
          </el-form-item>
        </el-col>
        <el-col class="line" :span="1" style="text-align:center;">-</el-col>
        <el-col :span="5">
          <el-form-item prop="couponEndTime">
            <el-date-picker v-model="form.couponEndTime" type="date" placeholder="选择结束日期" style="width: 100%;" :picker-options="pickerOptions" />
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="参与机构">
        <el-radio v-model="form.couponUsingRange" label="0">全部机构</el-radio>
        <el-radio v-model="form.couponUsingRange" label="1">部分机构</el-radio> <el-button v-show="form.couponUsingRange === '1'" type="text" style="position:relative;left: -20px;" @click="partOfAgency">修改</el-button>
        <div v-for="item in hasChooseAgencyList" v-show="form.couponUsingRange === '1'" :key="item.id">
          <label>{{ item.name }}</label>
        </div>
      </el-form-item>
      <el-form-item label="活动金额">
        <el-input v-model="form.activityAmount" clearable placeholder="请输入活动金额" />
      </el-form-item>
      <el-form-item label="优惠券">
        <div v-for="(item, index) in form.bonus" :key="index">
          <label>金额</label><el-input v-model="item.couponMoney" clearable placeholder="请输入" style="width:120px;margin-left:10px;" />&nbsp;&nbsp;&nbsp;
          <label>概率</label><el-input v-model="item.probability" clearable placeholder="请输入" style="width:120px;margin-left:10px;" /><p />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="800px"
    >
      <div style="margin-bottom: 20px;">
        <el-input v-model="listQuery.keyword" placeholder="请输入名称" style="width: 200px;" class="filter-item" clearable @keyup.enter.native="getList" />
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 20px;" @click="getList">
          搜索
        </el-button>
      </div>
      <el-table
        ref="multipleTable"
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        :element-loading-text="g.loadingStr"
        :header-cell-style="{background:g.mainColor}"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column label="序号" align="center" width="160" fixed>
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center">
          <template slot-scope="{row}">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="getList" />
    </el-dialog>

  </div>
</template>

<script>
import { prizePoolDetail, prizePoolAgencyList, prizePoolUpdate } from '@/api/prizePool'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  name: 'PrizePoolEdit',
  directives: { waves },
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        isCertified: 1,
        keyword: ''
      },

      rules: {
        activityName: [{ required: true, trigger: 'blur', validator: this.g.checkInputIsEmpty }],
        couponName: [{ required: true, trigger: 'blur', validator: this.g.checkInputIsEmpty }],
        activityStartTime: [{ type: 'date', required: true, message: '请选择活动开始日期', trigger: 'change' }],
        activityEndTime: [{ type: 'date', required: true, message: '请选择活动结束日期', trigger: 'change' }],
        couponStartTime: [{ type: 'date', required: true, message: '请选择优惠券开始日期', trigger: 'change' }],
        couponEndTime: [{ type: 'date', required: true, message: '请选择优惠券结束日期', trigger: 'change' }],
        activityAmount: [{ required: true, trigger: 'blur', validator: this.g.checkInputIsEmpty }]
      },

      form: {
        id: '',
        couponWay: 4,
        activityName: '',
        couponName: '',
        activityStartTime: null,
        activityEndTime: null,
        couponStartTime: null,
        couponEndTime: null,
        couponUsingRange: '0',
        activityAmount: '',
        businessIds: '',
        businessNames: '',
        bonus: []
      },
      dialogVisible: false,
      hasChooseAgencyList: []
    }
  },
  created() {
    this.form.id = this.$route.params['id']
    this.refresh()
  },
  mounted() {
  },
  methods: {
    refresh() {
      prizePoolDetail({ id: this.form.id }).then(response => {
        const data = response.data
        this.form.activityName = data.activityName
        this.form.couponName = data.couponName
        this.form.activityStartTime = new Date(data.activityStartTime)
        this.form.activityEndTime = new Date(data.activityEndTime)
        this.form.couponStartTime = new Date(data.couponStartTime)
        this.form.couponEndTime = new Date(data.couponEndTime)
        this.form.couponUsingRange = data.couponUsingRange + ''
        this.form.activityAmount = data.activityAmount
        this.form.bonus = JSON.parse(data.bonus)
        this.form.businessIds = data.businessIds.split(',')
        this.form.businessNames = data.businessNames.split(',')
      })
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.goToSubmit()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    goToSubmit() {
      console.log(this.form.bonus)

      let priceCheck = true
      let probabilityCheck = true
      this.form.bonus.forEach(item => {
        if (isNaN(Number(item['couponMoney']))) {
          priceCheck = false
        }
        if (isNaN(Number(item['probability']))) {
          probabilityCheck = false
        }
      })
      if (!priceCheck) {
        this.$message({ message: '请输入有效金额', type: 'error' })
        return
      }
      if (!probabilityCheck) {
        this.$message({ message: '请输入有效概率', type: 'error' })
        return
      }

      const data = {}
      for (const item of Object.keys(this.form)) {
        data[item] = this.form[item]
      }
      data.activityStartTime = data.activityStartTime !== null ? data.activityStartTime.getTime() : data.activityStartTime
      data.activityEndTime = data.activityEndTime !== null ? data.activityEndTime.getTime() : data.activityEndTime
      data.couponStartTime = data.couponStartTime !== null ? data.couponStartTime.getTime() : data.couponStartTime
      data.couponEndTime = data.couponEndTime !== null ? data.couponEndTime.getTime() : data.couponEndTime

      const bonus = []
      let probability = 0
      data.bonus.forEach(item => {
        probability += parseInt(item['probability'])
        bonus.push({
          id: item['id'],
          couponMoney: item['couponMoney'],
          probability: item['probability']
        })
      })
      data.bonus = JSON.stringify(bonus)
      if (probability > 100) {
        this.$message({ message: '概率不能大于100%', type: 'error' })
        return
      }

      if (this.form.couponUsingRange === '1') {
        const businessIds = []
        const businessNames = []
        this.hasChooseAgencyList.map(item => {
          businessIds.push(item['id'])
          businessNames.push(item['name'])
        })
        data.businessIds = businessIds.join(',')
        data.businessNames = businessNames.join(',')
      } else {
        data.businessIds = ''
        data.businessNames = ''
      }

      prizePoolUpdate(data).then(response => {
        this.$message({ message: '修改成功', type: 'success' })
        this.$router.push({ name: 'PrizePoolList' })
      })
    },
    partOfAgency() {
      this.dialogVisible = true
      this.getList()
    },
    getList() {
      this.listLoading = true
      prizePoolAgencyList(this.listQuery).then(response => {
        console.log(response.data)
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false

        this.$nextTick(() => {
          this.$refs.multipleTable.clearSelection()
          for (const item of this.list) {
            for (const row of this.hasChooseAgencyList) {
              if (item['id'] === row['id']) {
                this.$refs.multipleTable.toggleRowSelection(item)
              }
            }
          }
        })
      })
    },
    handleSelectionChange(val) {
      console.log(val.length)

      this.$nextTick(() => {
        const that = this
        const list = this.hasChooseAgencyList.filter(item => {
          let hasData = false
          that.list.map(row => {
            if (row['id'] === item['id']) {
              hasData = true
            }
          })
          return !hasData
        })
        this.hasChooseAgencyList = list.concat(val)
      })
    }
  }
}
</script>

<style lang="scss">
</style>
